package com.guli.gulimall.order.listener;

import com.guli.gulimall.order.config.AlipayTemplate;
import com.guli.gulimall.order.entity.OrderEntity;
import com.guli.gulimall.order.service.OrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Slf4j
@RabbitListener(queues = "order-event-exchange")
@Service
public class OrderCloseListener {

    @Autowired
    OrderService orderService;

    @Autowired
    AlipayTemplate alipayTemplate;

    /**
     * 关闭过期的订单
     *
     * @param entity
     * @param channel
     * @param message
     * @throws IOException
     */
    @RabbitListener(queues = "order.release.order.queue")
    public void listener(OrderEntity entity, Channel channel, Message message) throws IOException {
        System.out.println("收到过期的订单信息，准备关闭订单：" + entity.getOrderSn());
        try {
            orderService.closeOrder(entity);
            //todo 手动调用支付宝收单
            String result = alipayTemplate.receipt(entity.getOrderSn());
            log.info("支付宝[{}]自动收单结果：{}", entity.getOrderSn(), result);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            //关闭失败，消息回到队列
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }
}
